<!--时间段管理-->

<template>
  <div class="log">
    <basic-container>
      <avue-crud
          ref="crud"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :permission="permissionList"
          :table-loading="tableLoading"
          @search-reset="searchReset"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @row-update="handleUpdate"
          @row-save="handleSave"
          @row-del="handleDel">
        <template slot="menuLeft">
          <el-button
              class="filter-item"
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="addHandle()">新增
          </el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
              class="filter-item"
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="editHandle(scope.row)">编辑
          </el-button>
          <el-button
              class="filter-item"
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDel(scope.row)">删除
          </el-button>
        </template>
        <template slot="state" slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="danger">{{ scope.label }}</el-tag>
          <el-tag v-else type="success">{{ scope.label }}</el-tag>
        </template>
        <template slot="week" slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <template slot="inTimeBuild" slot-scope="scope">
          <span v-if="scope.row.inTime !== null">{{ scope.row.inTime }}</span>
          <span v-else>{{ scope.row.timeInBuild }}</span>
        </template>
        <template slot="outTimeBuild" slot-scope="scope">
          <span v-if="scope.row.outTime !== null">{{ scope.row.outTime }}</span>
          <span v-else>{{ scope.row.timeOutBuild }}</span>
        </template>
      </avue-crud>

      <el-dialog
          :visible.sync="dialogFormVisible"
          title="新增"
          width="40%"
          center @close="dictItemVisible">
        <el-form v-model="addform" :rules="rules" style="padding-left: 20px">
          <el-form-item label="通行区域属性" prop="area">
            <!--            <el-radio-group >-->
            <!--            <el-radio v-model="addform.area" :label="0" value="0">全部</el-radio>-->
            <el-radio v-model="addform.area" :label="1" value="1">校门</el-radio>
            <el-radio v-model="addform.area" :label="2" value="2">宿舍</el-radio>
            <!--            </el-radio-group>-->
          </el-form-item>
          <el-form-item label="时间段名称" prop="timeSectionName">
            <el-input v-model="addform.timeSectionName" placeholder="请输入时间段名称" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="请选择进向时间" prop="inTimearr">
            <el-time-picker
                v-model="inTimearr"
                end-placeholder="结束时间"
                is-range
                placeholder="选择时间范围"
                range-separator="至"
                start-placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="请选择出向时间" prop="outTimearr">
            <el-time-picker
                v-model="outTimearr"
                end-placeholder="结束时间"
                is-range
                placeholder="选择时间范围"
                range-separator="至"
                start-placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="指定起止日期">
            <el-col :span="8">
              <avue-date v-model="addform.scheduleTimeStart" format="yyyy年MM月dd日" placeholder="请选择开始日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
            <el-col :span="8">
              <avue-date v-model="addform.scheduleTimeEnd" format="yyyy年MM月dd日" placeholder="请选择结束日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
          </el-form-item>
          <el-form-item label="有效时间（多选）" prop="weeks">
            <el-checkbox-group v-model="weeks">
              <el-checkbox-button label="1" value="周一">周一</el-checkbox-button>
              <el-checkbox-button label="2" value="周二">周二</el-checkbox-button>
              <el-checkbox-button label="3" value="周三">周三</el-checkbox-button>
              <el-checkbox-button label="4" value="周四">周四</el-checkbox-button>
              <el-checkbox-button label="5" value="周五">周五</el-checkbox-button>
              <el-checkbox-button label="6" value="周六">周六</el-checkbox-button>
              <el-checkbox-button label="7" value="周日">周日</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
              class="filter-item"
              size="small"
              @click="dictItemVisible()">取消
          </el-button>
          <el-button
              class="filter-item"
              size="small"
              type="primary"
              @click="handleSave()">确定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
          :visible.sync="dialogEditVisible"
          title="编辑"
          width="40%"
          center @close="dictEditVisible">
        <el-form v-model="editform" style="padding-left: 20px">
          <el-form-item label="通行区域属性">
            <el-radio v-model="editform.area" :label="1" :value="1">校门</el-radio>
            <el-radio v-model="editform.area" :label="2" :value="2">宿舍</el-radio>
          </el-form-item>
          <el-form-item label="时间段名称">
            <el-input v-model="editform.timeSectionName" placeholder="请输入时间段名称" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="请输入进向时间">
            <el-time-picker
                v-model="inTimearr"
                end-placeholder="结束时间"
                is-range
                placeholder="选择时间范围"
                range-separator="至"
                start-placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="请输入出向时间">
            <el-time-picker
                v-model="outTimearr"
                end-placeholder="结束时间"
                is-range
                placeholder="选择时间范围"
                range-separator="至"
                start-placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="指定起止日期">
            <el-col :span="8">
              <avue-date v-model="editform.scheduleTimeStart" format="yyyy年MM月dd日" placeholder="请选择开始日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
            <el-col :span="8">
              <avue-date v-model="editform.scheduleTimeEnd" format="yyyy年MM月dd日" placeholder="请选择结束日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
          </el-form-item>
          <el-form-item label="有效时间（多选）">
            <el-checkbox-group v-model="weeks">
              <el-checkbox-button label="1" value="周一">周一</el-checkbox-button>
              <el-checkbox-button label="2" value="周二">周二</el-checkbox-button>
              <el-checkbox-button label="3" value="周三">周三</el-checkbox-button>
              <el-checkbox-button label="4" value="周四">周四</el-checkbox-button>
              <el-checkbox-button label="5" value="周五">周五</el-checkbox-button>
              <el-checkbox-button label="6" value="周六">周六</el-checkbox-button>
              <el-checkbox-button label="7" value="周日">周日</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
              class="filter-item"
              size="small"
              @click="dictEditVisible()">取消
          </el-button>
          <el-button
              class="filter-item"
              size="small"
              type="primary"
              @click="handleUpdate()">确定
          </el-button>
        </div>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {AddTimeslotObj, beforeEditObj, DelTimeSlotObj, EditTimeslotObj, timeSlotObj} from '@/api/pass/time-slot'
import {mapGetters} from 'vuex'
import {TIMESLOT_AREA, TIMESLOT_BIND, TIMESLOT_STATE, TIMESLOT_WEEK} from '@/const/Dict'

export default {
  name: 'time-slot',
  data() {
    return {
      checkList: [],
      inTimearr: '',
      outTimearr: '',
      dialogFormVisible: false,      //新增弹窗
      dialogEditVisible: false,
      tableData: [],
      searchForm: {},

      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableLoading: false,
      // tableOption: tableOption,
      weeks: [],
      addform: {
        area: '',
        inTime: '',
        outTime: '',
        timeSectionName: '',
        week: '',
        scheduleTimeEnd: '',
        scheduleTimeStart: ''
      },
      editform: {
        id: '',
        inTime: '',
        outTime: '',
        timeSectionName: '',
        week: '',
        area: '',
        scheduleTimeEnd: '',
        scheduleTimeStart: ''
      },
      rules: {  //必填项（验证规则）
        area: [
          {required: true, trigger: "none"}
        ],
        timeSectionName: [
          {required: true, trigger: "none"}
        ],
        inTimearr: [
          {required: true, trigger: "none"}
        ],
        outTimearr: [
          {required: true, trigger: "none"}
        ],
        weeks: [
          {required: true, trigger: "none"}
        ],
      },
      tableOption: {
        border: true,
        index: true,
        indexLabel: '序号',
        stripe: true,
        menuAlign: 'center',
        menuWidth: 210,
        menuType: 'button',
        align: 'center',
        emptyBtnText: '重置', //清空按钮文案
        refreshBtn: true,
        showClomnuBtn: false,
        searchSize: 'mini',
        searchMenuSpan: 4,
        searchLabelWidth: 100,
        searchSpan: 4,
        labelWidth: "20%",
        addBtn: false,
        editBtn: false,
        delBtn:false,
        viewBtn: false,
        selection: true,
        excelBtn: false,
        props: {
          label: 'label',
          value: 'value'
        },
        column: [
          {
            label: '时间段名',
            prop: 'timeSectionName',
            type: 'input',
            search: true,
          }, {
            width: 100,
            label: '通行区域属性',
            prop: 'area',
            type: 'select',
            search: true,
            dicData: TIMESLOT_AREA,
            change: (value) => {
              this.searchForm.area = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
            width: 110,
            label: '进向时间',
            prop: 'inTimeBuild',
            slot: true,
          }, {
            width: 110,
            label: '出向时间',
            prop: 'outTimeBuild',
            slot: true,
          }, {
            label: '指定开始时间',
            prop: 'scheduleTimeStart',
            search: false,
            type: "date",
            hide: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
              shortcuts: [{
                text: '今天',
                onClick(picker) {
                  picker.$emit('pick', new Date());
                }
              }]
            },
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd",
          }, {
            label: '指定结束时间',
            prop: 'scheduleTimeEnd',
            search: false,
            type: "date",
            hide: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
              shortcuts: [{
                text: '今天',
                onClick(picker) {
                  picker.$emit('pick', new Date());
                }
              }]
            },
            format: "yyyy-MM-dd hh:mm:ss",
            valueFormat: "yyyy-MM-dd",
          }, {
            width: 230,
            label: '生效时间',
            prop: 'week',
            dicData: TIMESLOT_WEEK,
            slot: true,
          }, {
            width: 130,
            label: '创建时间',
            prop: 'createTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
          }, {
            width: 94,
            label: '时间属性',
            prop: 'state',
            type: 'select',
            dicData: TIMESLOT_STATE,
            search: true,
            slot: true,
            change: (value) => {
              this.searchForm.state = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
            width: 100,
            label: '绑定方案',
            prop: 'binding',
            dicData: TIMESLOT_BIND,
            search: true,
            type: 'select',
            addDisplay: false,
            change: (value) => {
              this.searchForm.binding = value.value
              this.getList(this.page, this.searchForm)
            },
          }

        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permissions.sys_time_del, true),
      }
    }
  },
  methods: {
    //新增弹窗相关
    addHandle() {
      this.dialogFormVisible = true
    },
    //点击新增的关闭
    dictItemVisible: function () {
      this.dialogFormVisible = false
      this.addform = {}
      this.inTimearr = ''
      this.outTimearr = ''
      this.weeks = []
    },
    //点击编辑的关闭
    dictEditVisible: function () {
      this.dialogEditVisible = false
      this.editform = {}
      this.inTimearr = ''
      this.outTimearr = ''
      this.weeks = []
    },
    getList(page, params) {
      this.tableLoading = true
      timeSlotObj(Object.assign({
        descs: 'create_time',  //是否倒序
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      })
    },
    handleSave: function (row, done) {
      // debugger
      if (this.addform.area === ''){
        this.$message.error('添加失败，请选择通行区域')
        return
      }
      if (this.addform.timeSectionName === ''){
        this.$message.error('添加失败，请输入时间段名称')
        return
      }
      if (this.inTimearr === ''){
        this.$message.error('添加失败，请选择进向时间')
        return
      }
      if (this.outTimearr === ''){
        this.$message.error('添加失败，请选择出向时间')
        return
      }
      if (this.weeks.length === 0){
        this.$message.error('添加失败，请选择有效时间')
      }
      // debugger
      // console.log(this.weeks)
      this.weeks.sort()
      // console.log(this.weeks)
      this.addform.week = this.weeks.toString()
      console.log(this.addform.week)
      // this.addform.inTime = this.inTimearr[0] + '-' + this.inTimearr[1]  //两种转换方式
      this.addform.inTime = this.inTimearr.join("-")
      // this.addform.outTime = this.outTimearr[0] + '-' + this.outTimearr[1]
      this.addform.outTime = this.outTimearr.join("-")
      console.log(this.addform)
      AddTimeslotObj(this.addform).then(res => {
        if (res.data.code === 0) {
          this.dialogFormVisible = false
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败')
        }
        // done()
        this.addform = {}
        this.getList(this.page)
      })
    },
    //编辑相关
    editHandle(row) {
      this.id = row.id
      this.dialogEditVisible = true
      beforeEditObj(this.id).then(response => {
        if (response.data.code === 0) {
          this.editform = response.data.data
          // 将后台的字符串转换为日期的数组并展示
          if (response.data.data.inTime && response.data.data.outTime !== null) {
            this.inTimearr = response.data.data.inTime.split("-")
            this.outTimearr = response.data.data.outTime.split("-")
          } else {
            this.inTimearr = response.data.data.timeInBuild.split("-")
            this.outTimearr = response.data.data.timeOutBuild.split("-")
          }
          // if (response.data.data.week != null && response.data.data.week != ""){
          this.weeks = response.data.data.week.split(",")
          // }
          console.log(this.weeks)
          // console.log(this.outTimearr)
        }
      })
    },

    handleUpdate: function (row, index, done) {
      // debugger
      this.dialogEditVisible = false
      //  编辑时将空值删除，再将所选的进行排序；
      //  将进出向时间先进行非空判断，再将校门和宿舍的进出向进行区分
      var arr = this.weeks
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == '' || arr[i] == ',' || typeof (arr[i]) == undefined) {
          arr.splice(i, 1);
          i = i - 1;
        }
      }
      // console.log(arr)
      arr.sort()
      this.editform.week = arr.toString()
      if (this.inTimearr && this.outTimearr !== null) {
        this.editform.inTime = this.inTimearr.join("-")
        this.editform.outTime = this.outTimearr.join("-")
      } else {
        this.editform.timeInBuild = this.inTimearr.join("-")
        this.editform.timeOutBuild = this.outTimearr.join("-")
      }

      // let param = {
      //   "id": this.editform.id,
      //   "inTime": this.editform.inTime,
      //   "outTime": this.editform.outTime,
      //   "area": this.editform.area,
      //   "timeSectionName": this.editform.timeSectionName,
      //   "week": this.editform.week,
      // }
      console.log(this.editform)
      EditTimeslotObj(this.editform).then(res => {
        if (res.data.code === 0) {
          this.$message.success('修改成功')
        } else {
          this.$message.error('修改失败')
        }
        // done()
        this.editform = {}
        this.getList(this.page)
      })
    },
    handleDel: function (row) {
      this.$confirm('是否确认删除"' + row.timeSectionName + '"的时间段?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return DelTimeSlotObj(row.id)
      }).then(() => {
        this.getList(this.page)
        this.$message.success('删除成功')
      })
    },
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    refreshChange() {
      this.getList(this.page)
    },
    searchReset(){
      this.searchForm = {};
      this.getList(this.page)
    }
  }
}
</script>
<style scoped>
/deep/.el-form-item__label{
text-align: left;
}
/deep/.avue-form__row{
padding-left: 4px !important;
margin-right: 36px;
}
/deep/.avue-form__menu--center{
  text-align: left;
}
/deep/.avue-form__menu--center .el-button{
  margin: 0 20px 0 0;
}
</style>